<template>
  <div class="container">
    <avue-crud
      ref="avueRef"
      :option="option"
      :data="data"
      :page.sync="page"
      @search-change="searchchange"
      :before-close="beforeClose"
      @size-change="sizeChange"
      @current-change="currentChange"
      @row-update="rowUpdate"
    >
      <template #search-menu="{ row, size }">
        <!-- <el-button @click="clickAdd1()">新增工程</el-button> -->
        <el-button @click="clickAdd()">新增管线</el-button>
      </template>
      <template #menu="{ row, index }">
        <el-button link type="primary" @click.stop="clickBtn(row, 3, index)"
          >编辑</el-button
        >
        <el-button link type="primary" @click.stop="clickBtn(row, 1)"
          >删除</el-button
        >
      </template>
    </avue-crud>
    <el-dialog
      v-model="addVisible"
      title="管线新增"
      width="1200px"
      class="avue-dialog"
      draggable
      destroy-on-close
      :modal="false"
      :close-on-click-modal="false"
    >
      <div class="map-box">
        <div class="fl">
          <div class="tips">选择工程</div>
          <div class="mt-4">
            <el-select
              v-model="dialogObj.id"
              placeholder="请选择工程"
              filterable
              size="small"
              style="max-width: 180px; margin: 10px 0"
              @change="changeSelect"
            >
              <el-option
                v-for="item in dialogObj.gcList"
                :key="item.id"
                :label="item.text"
                :value="item.id"
              />
            </el-select>
          </div>
          <div class="tips">操作工具</div>
          <div class="mt-4">
            <el-input
              v-model="dialogObj.qd"
              style="max-width: 180px; margin: 10px 0"
              disabled
              type="textarea"
              placeholder="请在地图选择"
            >
            </el-input>
            <el-button
              type="primary"
              size="small"
              @click.stop="clickBtnCz('起点')"
              >选择起点</el-button
            >
          </div>
          <div class="mt-4">
            <el-input
              v-model="dialogObj.zd"
              style="max-width: 180px; margin: 10px 0"
              disabled
              type="textarea"
              placeholder="请在地图选择"
            >
            </el-input>
            <el-button
              type="danger"
              size="small"
              @click.stop="clickBtnCz('终点')"
              >选择终点</el-button
            >
          </div>
          <div class="tips">温馨提示</div>
          <div class="mt-4">
            <div class="item">
              已绘制管线:
              <div class="line"></div>
            </div>
          </div>
        </div>
        <div class="fr">
          <olMap :objProps="objProps" @updateEmits="updateEmits"></olMap>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button :loading="loadingBtn" type="primary" @click="clickSave"
            >保 存</el-button
          >
          <el-button @click="handleClose">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="addVisible1"
      title="工程新增"
      width="1200px"
      class="avue-dialog"
      draggable
      destroy-on-close
      :modal="false"
      :close-on-click-modal="false"
    >
      <el-form
        :model="formGc"
        ref="ruleFormRef"
        :rules="rules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="工程名称" prop="name">
          <el-input v-model="formGc.name" />
        </el-form-item>
        <el-form-item label="工程编号" prop="gch">
          <el-input v-model="formGc.gch" />
        </el-form-item>
        <el-form-item label="省" prop="sheng">
          <el-input v-model="formGc.sheng" />
        </el-form-item>
        <el-form-item label="市" prop="shi">
          <el-input v-model="formGc.shi" />
        </el-form-item>
        <el-form-item label="县" prop="xian">
          <el-input v-model="formGc.xian" />
        </el-form-item>
        <el-form-item label="压力" prop="yl">
          <el-input v-model="formGc.yl" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="formGc.type"
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option label="RQ" value="RQ" />
            <el-option label="DL" value="DL" />
          </el-select>
        </el-form-item>
        <el-form-item label="子类型" prop="pipType">
          <el-select
            v-model="formGc.pipType"
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option label="TR" value="TR" />
          </el-select>
        </el-form-item>
        <el-form-item label="建设日期" prop="jsDate"
          ><el-date-picker
            v-model="formGc.jsDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button :loading="loadingBtn" type="primary" @click="clickSave1"
            >保 存</el-button
          >
          <el-button @click="handleClose1">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { ElMessage, ElMessageBox, formProps } from 'element-plus'
import olMap from '@/components/olMap/olMap.vue'
import { request } from '@/utils/request'
import ManageService from '@/service/manage.service'
import * as row from './pipeline.js'
const state = reactive({
  page: {
    size: 10,
    current: 1
  },
  total: 0,
  data: row.data,
  option: row.option,
  optionsAddress: [],
  propsAddress: {
    label: 'name',
    value: 'name'
  },
  formAddress: [],
  addVisible: false,
  addVisible1: false,
  loadingBtn: false,
  formGc: {
    name: '',
    gch: '',
    sheng: '',
    shi: '',
    xian: '',
    yl: '',
    type: '',
    pipType: '',
    jsDate: ''
  }
})
const objProps = ref({
  type: '',
  coordinates: '',
  type1: ''
})
const dialogObj = ref({
  qd: '',
  zd: '',
  dqType: '',
  id: '',
  gcList: []
})
const rules = ref({
  name: [{ required: true, message: '请输入', trigger: 'blur' }],
  gch: [{ required: true, message: '请输入', trigger: 'blur' }],
  sheng: [{ required: true, message: '请输入', trigger: 'blur' }],
  shi: [{ required: true, message: '请输入', trigger: 'blur' }],
  xian: [{ required: true, message: '请输入', trigger: 'blur' }],
  yl: [{ required: true, message: '请输入', trigger: 'blur' }],
  type: [{ required: true, message: '请选择', trigger: 'change' }],
  pipType: [{ required: true, message: '请选择', trigger: 'change' }],
  jsDate: [{ required: true, message: '请输入', trigger: 'blur' }]
})
const {
  data,
  page,
  option,
  optionsAddress,
  propsAddress,
  formAddress,
  addVisible,
  addVisible1,
  loadingBtn,
  formGc
} = toRefs(state)
const beforeClose = (done) => {
  state.option = JSON.parse(JSON.stringify(row.option))
  done()
}
const avueRef = ref(null)
const searchchange = (row, done) => {
  state.page.current = 1
  state.searchForm = {
    like: {}
  }
  if (row.likeGch) {
    state.searchForm.like.gch = row.likeGch
  }
  if (row.likeStartPoint) {
    state.searchForm.like.startPoint = row.likeStartPoint
  }
  if (row.likeEndPoint) {
    state.searchForm.like.endPoint = row.likeEndPoint
  }
  if (!row.likeGch && !row.likeStartPoint && !row.likeEndPoint) {
    state.searchForm = ''
  }
  initData()
  done()
}
const clickBtnCz = (val) => {
  ElMessage({
    message: `请在地图上获取${val}坐标`,
    type: 'info'
  })
  objProps.value.type = '获取左键单击坐标'
  dialogObj.value.dqType = val
}
const changeSelect = () => {
  const index = dialogObj.value.gcList.findIndex((e) => {
    return e.id === dialogObj.value.id
  })
  const arr = dialogObj.value.gcList[index]
  request({
    url: '/region/getGeom',
    method: 'get',
    params: {
      sheng: arr.sheng,
      shi: arr.shi,
      xian: arr.xian
    }
  }).then((res) => {
    if (res.code == 200) {
      if (!res.data) {
        ElMessage.error('未查到中心点')
      } else {
        objProps.value.coordinates = res.data.centre.coordinates
        objProps.value.type = '跳转中心点'
        setTimeout(() => {
          objProps.value.coordinates = arr.gch
          objProps.value.type = '绘制wms'
        }, 100)
      }
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const updateEmits = (obj) => {
  if (obj.type === '坐标获取') {
    objProps.value.coordinates = obj.coordinate
    objProps.value.type = '加载图标'
    objProps.value.type1 = dialogObj.value.dqType
    if (dialogObj.value.dqType === '起点') {
      dialogObj.value.qd = obj.coordinate
    } else {
      dialogObj.value.zd = obj.coordinate
    }
    setTimeout(() => {
      if (dialogObj.value.qd && dialogObj.value.zd) {
        objProps.value.type = '加载线段'
        objProps.value.coordinates = [dialogObj.value.qd, dialogObj.value.zd]
      }
    }, 50)
  }
}
const getApi = () => {
  request({
    url: '/engineering/page',
    method: 'post',
    data: {}
  }).then((res) => {
    if (res.code == 200) {
      res.data.records.forEach((item) => {
        item.text = `${item.gch}-${item.shi}-${item.xian}`
      })
      dialogObj.value.gcList = res.data.records
      const list = res.data.records.map((item) => {
        return {
          value: item.gch,
          label: `${item.gch}-${item.shi}-${item.xian}`
        }
      })
      option.value.column[2].dicData = list
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const clickAdd1 = () => {
  addVisible1.value = true
}
const clickAdd = () => {
  dialogObj.value.qd = ''
  dialogObj.value.zd = ''
  dialogObj.value.id = ''
  dialogObj.value.dqType = ''
  objProps.value.type = ''
  addVisible.value = true
  setTimeout(() => {
	  objProps.value.type = "加载初始图层管线"
  }, 100)
}
const handleClose = () => {
  addVisible.value = false
}
const handleClose1 = () => {
  addVisible1.value = false
}
const ruleFormRef = ref(null)
const clickSave1 = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      request({
        url: '/engineering/add',
        method: 'post',
        data: {
          ...formGc.value
        }
      }).then((res) => {
        if (res.code == 200) {
          loadingBtn.value = false
          addVisible1.value = false
          ElMessage({
            message: '保存成功',
            type: 'success'
          })
        } else {
          loadingBtn.value = false
          ElMessage.error(res.msg)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const clickSave = () => {
  if (!dialogObj.value.id) {
    ElMessage({
      message: '请先选择工程',
      type: 'error'
    })
    return
  }
  if (!dialogObj.value.qd) {
    ElMessage({
      message: '请先选择起点',
      type: 'error'
    })
    return
  }
  if (!dialogObj.value.zd) {
    ElMessage({
      message: '请先选择终点',
      type: 'error'
    })
    return
  }
  loadingBtn.value = true
  // const qds = dialogObj.value.qd.split(',')
  // const zds = dialogObj.value.zd.split(',')
  const coordinates = [
    {
      x: dialogObj.value.qd[0],
      y: dialogObj.value.qd[1],
      dmGc: 0
    },
    {
      x: dialogObj.value.zd[0],
      y: dialogObj.value.zd[1],
      dmGc: 0
    }
  ]
  request({
    url: '/analysis/protract',
    method: 'post',
    data: {
      coordinates: coordinates,
      id: dialogObj.value.id
    }
  }).then((res) => {
    if (res.code == 200) {
      loadingBtn.value = false
      addVisible.value = false
      initData()
      ElMessage({
        message: '保存成功',
        type: 'success'
      })
    } else {
      loadingBtn.value = false
      ElMessage.error(res.msg)
    }
  })
}
//操作栏按钮
const clickBtn = (row, type, index) => {
  if (type === 1) {
    ElMessageBox.confirm('确认删除该条数据?', '温馨提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      request({
        url: '/pop/line_del',
        method: 'get',
        params: {
          id: row.id
        }
      }).then((res) => {
        if (res.code == 200) {
          initData()
          ElMessage({
            message: '删除成功',
            type: 'success'
          })
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  } else if (type === 3) {
    avueRef.value.rowEdit(row, index)
  }
}
//列表查询
const initData = async () => {
  const params = new URLSearchParams(sessionStorage.getItem('xzq'))
  // 将 URLSearchParams 转换为普通对象
  let obj = {}
  params.forEach((value, key) => {
    obj[key] = value
  })
  if (state.searchForm?.like) {
    obj = {
      ...obj,
      gch: state.searchForm.like?.gch,
      startPoint: state.searchForm.like?.startPoint,
      endPoint: state.searchForm.like?.endPoint
    }
  }
  request({
    method: 'post',
    url: '/pop/line_page',
    data: {
      // ...state.searchForm,
      ...state.page,
      query: {
        ...obj
      }
    }
  }).then((res) => {
    state.data = res.data.records
    state.page.total = res.data.total
  })
}
//编辑保存
const rowUpdate = (row, index, done, loading) => {
  request({
    method: 'post',
    url: '/pop/line_edit',
    data: {
      ...row
    }
  })
    .then((res) => {
      loading()
      if (res.code === 200) {
        ElMessage({
          message: '修改成功',
          type: 'success'
        })
        done()
        initData()
      } else {
        ElMessage(res.msg)
      }
    })
    .catch((error) => {
      console.log(error)
      loading()
    })
}
//分页查询--条数
const sizeChange = (val) => {
  page.value.size = val
  page.value.current = 1
  initData()
}
//分页查询--页码
const currentChange = (val) => {
  page.value.current = val
  initData()
}
onMounted(() => {
  initData()
  getApi()
})
</script>

<style lang="scss" scoped>
.container {
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
}
:deep(div.el-table__body-wrapper) {
  height: calc(100vh - 260px);
  flex: none;
}

.avue-crud__pagination .el-pagination {
  margin-right: 10px;
}
:deep(.el-card) {
  border-radius: 0;
}
:deep(.avue-crud__header) {
  display: none;
}
:deep(.avue-form__menu) {
  display: contents !important;
}
.map-box {
  height: 620px;
  width: 100%;
  display: flex;
  .fl {
    width: 200px;
    .mt-4 {
      margin: 10px 0;
      .item {
        display: flex;
        align-items: center;
        .line {
          width: 100px;
          height: 5px;
          margin-left: 10px;
          background-color: #ff00ff;
        }
      }
    }
  }
  .fr {
    width: calc(100% - 200px);
  }
}
:deep(.avue-dialog) .el-dialog__body {
  overflow: auto;
  padding: 20px;
}
</style>
